<template>
  <div style="page-break-inside:avoid;">
    <ReportEcharts :option="option" :id="id" :imgList="sleepImg" :bigFontFlag="props.bigFontFlag"/>
  </div>
</template>

<script setup lang="ts">
import {getCurrentInstance, reactive, ref, toRefs, watch} from 'vue'
import {ReportEcharts} from "@/components/ReportEcharts";

interface sleepType {
  reportData: any,
  bigFontFlag: boolean
}

const props = defineProps<sleepType>()

type EChartsOption = echarts.EChartsOption
const {proxy} = getCurrentInstance() as any
const echarts = proxy.$echarts

interface DataType {
  option: EChartsOption
}

const sleepImg = ref()

const colors = ['#722ED1', '#14C9C9', '#F5319D', '#00A991'] //状态的颜色

const state = ['离床', '清醒', '浅睡', '深睡'] //状态

const id = ('sleepEcharts' + Math.random()).replace(".", "")
const data = reactive<DataType>({
  option: {}
})
let {option} = toRefs(data)
const lastStatus = ref(0)
let mainDateTime = ref<string>('')

const itemStyle = (obj: any) => {
  let arr = obj?.stageRecordsList || []
  let mainData : any = [];
  lastStatus.value = 0;
  mainDateTime.value = '';
  if (arr.length > 0) {
    arr.forEach((val, i) => {
      val.sleepStage = Number(val.sleepStage)
      let createDate: string = timestampToTime(val.acquisitionTime, false, false)
      let createTime: string = timestampToTime(val.acquisitionTime, true, false)
      if (lastStatus.value == val.sleepStage) {
        mainData[mainData.length - 1].value[2] = createTime.replace('-', '/')
      } else {
        let lastTime: string | number = ''
        if (i == 0) {
          lastStatus.value = val.sleepStage
          let time = createDate + ' 18:00:00'
          //判断初始时间是否为凌晨
          if (getHour(time, val.acquisitionTime)) {
            createDate = dateChange(-1, createDate)
          }
          lastTime = createDate.replace('-', '/') + ' 18:00'
          mainDateTime.value = createDate.replace('-', '/')
        } else {
          lastTime = mainData[mainData.length - 1].value[2]
        }
        let item = {
          itemStyle: {
            color: colors[getStatus(val.sleepStage)]
          },
          name: getType(val.sleepStage),
          value: [getStatus(val.sleepStage) + 1, lastTime, createTime.replace('-', '/')]
        }
        mainData.push(item)
      }
      lastStatus.value = val.sleepStage
    })
  }
  setOption(mainData)
}

const setOption = (datas : any) => {
  option.value = {
    color: colors,
    tooltip: {
      //提示框
      formatter: function (params) {
        return params.name + ':' + params.value[1] + '~' + params.value[2]
      } //数据的值
    },
    legend: {
      //图例
      data: state,
      left: 'left',
      bottom: '-2%',
      icon: 'rect',
      itemHeight: 8,
      itemWidth: 8,
      selectedMode: false, // 图例设为不可点击
      textStyle: {
        color: '#626266',
        fontSize: (props.bigFontFlag ? "18px" : "")
      }
    },
    grid: {
      //绘图网格
      left: '0%',
      right: '4%',
      top: '-5%',
      bottom: '13%',
      containLabel: true
    },
    xAxis: {
      type: 'time',
      scale: true, // 不会强制包含零刻度。在双数值轴的散点图中比较有用
      interval: 3600 * 1000, //以一个小时递增
      min: mainDateTime.value + ' 18:00', //将data里最小时间的整点时间设为min,否则min会以data里面的min为开始进行整点递增
    },
    yAxis: {
      data: ['离床', '清醒', '浅睡', '深睡'],
      axisTick: {
        show: false //y轴刻度消失
      },
      axisLine: {
        show: false //y轴线消失
      }
    },
    series: [
      // 用空bar来显示三个图例
      {name: state[0], type: 'bar', data: []},
      {name: state[1], type: 'bar', data: []},
      {name: state[2], type: 'bar', data: []},
      {name: state[3], type: 'bar', data: []},
      {
        type: 'custom',
        renderItem: function (params: any, api: any) {
          //开发者自定义的图形元素渲染逻辑，是通过书写 renderItem 函数实现的
          var categoryIndex = api.value(0) - 1 //这里使用 api.value(0) 取出当前 dataItem 中第一个维度的数值。
          var start = api.coord([api.value(1), categoryIndex]) // 这里使用 api.coord(...) 将数值在当前坐标系中转换成为屏幕上的点的像素值。
          var end = api.coord([api.value(2), categoryIndex])
          var height = api.size([0, 1])[1]
          return {
            type: 'rect', // 表示这个图形元素是矩形。还可以是 'circle', 'sector', 'polygon' 等等。
            shape: echarts.graphic.clipRectByRect(
              {
                // 矩形的位置和大小。
                x: start[0],
                y: start[1] - height / 2,
                width: end[0] - start[0],
                height: params.coordSys.height
              },
              {
                // 当前坐标系的包围盒。
                x: params.coordSys.x,
                y: params.coordSys.y,
                width: params.coordSys.width,
                height: params.coordSys.height
              }
            ),
            style: api.style()
          }
        },
        encode: {
          x: [1, 2], // data 中『维度1』和『维度2』对应到 X 轴
          y: 0 // data 中『维度0』对应到 Y 轴
        },
        data: datas
      }
    ]
  }

  let obj = props.reportData
  sleepImg.value = [
    {
      url: 'fallAsleep.png',
      text: '睡眠时长',
      value: obj && obj.sleepDuration ? obj.sleepDuration : '-'
    },
    {
      url: 'deepSleep.png',
      text: '深睡时长',
      value: obj && obj.deepSleepDuration ? obj.deepSleepDuration : '-'
    },
    {
      url: 'lightSleep.png',
      text: '浅睡时长',
      value: obj && obj.lightSleepDuration ? obj.lightSleepDuration : '-'
    },
    {
      url: 'sober.png',
      text: '清醒时长',
      value: obj && obj.sleepWakingDuration ? obj.sleepWakingDuration : '-'
    },
    {
      url: 'goToBed.png',
      text: '上床时间',
      value: obj && obj.sleepTimeStr ? obj.sleepTimeStr : '-'
    },
    {
      url: 'getUp.png',
      text: '起床时间',
      value: obj && obj.wakeUpTimeStr ? obj.wakeUpTimeStr : '-'
    },
    {
      url: 'move.png',
      text: '体动情况',
      value: obj && obj.bodymoveStatus ? obj.bodymoveStatus : '-'
    },
    {
      url: 'offBed.png',
      text: '离床次数',
      value: (obj && obj.getUpCount ? obj.getUpCount : '-') + '次'
    }
  ]
}

//判断名字
function getType(status: number): string {
  var result = ''
  switch (status) {
    case 1:
      result = '清醒'
      break
    case 2:
      result = '浅睡'
      break
    case 3:
      result = '深睡'
      break
    default:
      result = '离床'
      break
  }
  return result
}

//判断状态
function getStatus(status: number): number {
  let statusNum = status
  if (status == 4) {
    statusNum = 0
  }
  return statusNum
}

function timestampToTime(timestamp: string, useHour: boolean, useSecond: boolean): string {
  let date = new Date(timestamp)
  let Y = date.getFullYear() + '-'
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  let D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let h = date.getHours() + ':'
  let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

  if (!useHour) return Y + M + D
  else {
    if (useSecond) return Y + M + D + ' ' + h + m + ':' + s
    else return Y + M + D + ' ' + h + m
  }
}

//比较时间
function getHour(startTime: string, endTime: string): boolean {
  let startTimes = startTime.substring(0, 10).split('-')
  let endTimes = endTime.substring(0, 10).split('-')
  startTime =
    startTimes[1] + '-' + startTimes[2] + '-' + startTimes[0] + ' ' + startTime.substring(10, 19)
  endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19)
  let thisResult = (Date.parse(endTime) - Date.parse(startTime)) / 3600 / 1000
  if (thisResult < 0) {
    return true
  } else if (thisResult > 0) {
    return false
  } else if (thisResult == 0) {
    return false
  } else {
    return false
  }
}

//日期减一天
function dateChange(num = 1, date: any = false): string {
  if (!date) {
    date = new Date() //没有传入值时,默认是当前日期
    date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
  }
  date += ' 00:00:00' //设置为当天凌晨12点
  date = Date.parse(new Date(date)) / 1000 //转换为时间戳
  date += 86400 * num //修改后的时间戳
  var newDate = new Date(parseInt(date) * 1000) //转换为时间
  return newDate.getFullYear() + '-' + (newDate.getMonth() + 1) + '-' + newDate.getDate()
}

itemStyle(props.reportData);
//监听reportData变化
watch(
  () => props.reportData,
  (newValue) => {
    itemStyle(newValue)
  },
  {
    deep: true
  }
)
</script>

<style scoped lang="less">
#refSleep {
  width: 75%;
  height: 290px;
}
</style>
